package com.fzdy.dataplatform.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.fzdy.dataplatform.controller.api.ModuleCallback;
import com.fzdy.dataplatform.controller.api.device.DeviceInfoApi;
import com.fzdy.dataplatform.core.common.AjaxCallback;
import com.fzdy.dataplatform.core.common.TimeStampTool;
import com.fzdy.dataplatform.core.controller.BaseController;
import com.fzdy.dataplatform.entity.Business;
import com.fzdy.dataplatform.entity.Device;
import com.fzdy.dataplatform.entity.DeviceOwner;
import com.fzdy.dataplatform.entity.NetWay;
import com.fzdy.dataplatform.service.*;
import com.fzdy.dataplatform.webutil.ExcelReader;
import com.fzdy.dataplatform.webutil.FileTool;
import com.fzdy.dataplatform.webutil.ObjListToExcel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;


@Controller
@RequestMapping(value = "/sysmanage/device")
public class UploadTest extends BaseController {
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private BusinessService businessService;
    @Autowired
    private ProductService productService;
    @Autowired
    private DeviceOwnerService deviceOwnerService;
    @Autowired
    private NetWayService netWayService;
    //处理文件上传
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile file, @RequestParam("businessid") int businessid,
                         HttpServletRequest request) {
        AjaxCallback ajaxCallback;
        Business business = businessService.get(businessid);
        if (business == null) {
            return JSON.toJSONString(new AjaxCallback(ModuleCallback.FAILURENO, "没有对应业务"));
        }
        if (!webUtilify.isAdmin(request) && !business.getUserid().equals(webUtilify.LoginUserinfo(request).getId())) {
            return JSON.toJSONString(new AjaxCallback(ModuleCallback.FAILURENO, "没有对应业务"));
        }

        try {
            String jsonString = ExcelReader.getContentFromXls((FileInputStream) file.getInputStream());
            List<DeviceInfoApi> deviceList = JSONArray.parseArray(jsonString, DeviceInfoApi.class);
            List<String> listSn = deviceList.stream().map(x -> x.getSn()).collect(Collectors.toList());
            List<Device> devices=deviceService.getListBySnList(listSn);
            List<NetWay> netWays = netWayService.getList();
            if (deviceList.size() > 0) {
                for (DeviceInfoApi dData : deviceList) {
                    if (devices.stream().anyMatch(data -> data.getSn().equals(dData.getSn()))) {
                        System.out.println(dData.getSn()+" device exist in db");
                    }else {
                        Device device = new Device();
                        device.setSn(dData.getSn());
                        device.GeneralParams(dData.getName(), dData.getImsi(), dData.getImei(), dData.getSim(), dData.getInfo(),
                                dData.getCoordinate(), dData.getLocation());
                        DeviceController.deviceSetBusinessAndparseKtv(device, business,productService);
                        for (NetWay net: netWays) {
                            if (net.getName().equals(dData.getNetway())){
                                device.setNetway(net);

                            }
                        }
                        device.setCreatedate(new Date());
                        device.setStatus(1);
                        deviceService.insertT(device);
                        DeviceOwner deviceOwner = new DeviceOwner(device.getSn(), business.getUserid(), 1);
                        deviceOwnerService.insertT(deviceOwner);
                    }
                }
            }
            ajaxCallback= new AjaxCallback();
        } catch (IOException e) {
            ajaxCallback = new AjaxCallback(ModuleCallback.FAILURENO, "文件出错");
            e.printStackTrace();
        }
        return JSON.toJSONString(ajaxCallback);
    }

    @RequestMapping(value = "/export")
    public void exportExcel(@RequestParam("businessid") int businessid, HttpServletRequest request, final HttpServletResponse response) throws ParseException, IOException {
        Business business = businessService.get(businessid);
//        if (!webUtilify.isAdmin(request)) {
//            if (!business.getUserid().equals(webUtilify.LoginUserinfo(request).getId())) {
//                return "fail";
//            }
//        }
        Device device = new Device();
        device.setBusinessid(business.getId());
        device.setStatus(1);
        List<Device> list = deviceService.findByExampleLike(device);
        List<DeviceInfoApi> listData = null;
        if (list.size() > 0) {
            listData = setToExcelApi(list);
            Map<String, Object> map = new HashMap<>();
            Map<String, String> ziDuan = new HashMap();
            ziDuan.put("0sn", "sn");
            ziDuan.put("1name", "name");
            ziDuan.put("2imsi", "imsi");
            ziDuan.put("3imei", "imei");
            ziDuan.put("4location", "location");
            ziDuan.put("5coordinate", "coordinate");
            ziDuan.put("6netway", "netway");
            ziDuan.put("7info", "info");
            map.put("listData", listData);
            map.put("ziDuan", ziDuan);
            File file = ObjListToExcel.objListToExcel("设备列表", map);
            byte[] b = FileTool.getBytesFromFile(file);
            //以字符流的形式下载文件
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=device-"
                    + TimeStampTool.DateToString("yyyy-MM-dd", new Date()) + ".xls");
            response.addHeader("content-type", "utf-8");
            response.addHeader("Content-Length", "" + b.length);
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(b);
            toClient.flush();
            toClient.close();
        }
    }


    private List<DeviceInfoApi> setToExcelApi(List<Device> list) {
        List<DeviceInfoApi> apis = new ArrayList<>();
        for (Device device : list) {
            DeviceInfoApi deviceInfoApi = new DeviceInfoApi(device.getSn(), device.getName(),
                    device.getImsi(), device.getImei(), device.getSim(), device.getInfo(), device.getCoordinate(),
                    device.getLocation(), device.getNetwayid(), 0);

            if (device.getNetway() != null)
                deviceInfoApi.setNetway(device.getNetway().getName());
            apis.add(deviceInfoApi);
        }
        return apis;
    }
}
